#include "TimeUtil.h"

#include <stddef.h>
#include <time.h>

/*!< 时间字符串话的结构 */
#define TIME_STRING_FORMAT "%04d-%02d-%02d %02d:%02d:%02d" 


#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif

int64_t CTimeUtil::m_lCurSecondTime = 0;
int64_t CTimeUtil::m_lCurMilliSecondTime = 0;

CTimeUtil::CTimeUtil()
{
}


CTimeUtil::~CTimeUtil()
{
}

void CTimeUtil::SetCurTime()
{
#ifdef _WIN32
    SYSTEMTIME sys;
    GetLocalTime(&sys);
    m_lCurSecondTime = sys.wSecond;
    m_lCurMilliSecondTime = sys.wMilliseconds;
#else
    struct timeval tv;
    gettimeofday(&tv, NULL);
    m_lCurSecondTime = tv.tv_sec;
    m_lCurMilliSecondTime = tv.tv_usec / 1000;
#endif
}

int64_t CTimeUtil::GetZeroInDay(int64_t llTimeStamp)
{
    struct tm * tm = localtime(&llTimeStamp);
    tm->tm_hour = 0;
    tm->tm_min = 0;
    tm->tm_sec = 0;
    return  mktime(tm);
}

string &CTimeUtil::TimeStamp2String(int64_t llTimeStamp)
{
    static string stTimeString;
    static struct tm tmTimeStruct;
    static char strTime[30];
    
    
    tmTimeStruct = *localtime((time_t *)&llTimeStamp);
    int iCount = strftime(strTime, sizeof(strTime), TIME_STRING_FORMAT, &tmTimeStruct);

    if (iCount >= sizeof(strTime))
    {
        stTimeString = "";
    }
    else
    {
        strTime[iCount] = '\0';
        stTimeString = strTime;
    }
    return stTimeString;
}



time_t CTimeUtil::String2TimeStamp(string stTimeString)
{
    static struct tm tmTimeStruct;
    memset(&tmTimeStruct, 0, sizeof(tmTimeStruct));

    sscanf(stTimeString.c_str(), TIME_STRING_FORMAT,
        &tmTimeStruct.tm_year, &tmTimeStruct.tm_mon, &tmTimeStruct.tm_mday,
        &tmTimeStruct.tm_hour, &tmTimeStruct.tm_min, &tmTimeStruct.tm_sec);

    tmTimeStruct.tm_year -= 1900;
    tmTimeStruct.tm_mon--;

    return mktime(&tmTimeStruct);
}